//
//  CMDBCalendarView.swift
//  CMDB
//
//  Created by 曹桂祥 on 2017/5/17.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

private let CalendarID = "DIYCalendarCell"

class CMDBCalendarView: FSCalendar {
    
    var eventLabel : UILabel!
    
    var gregorian : NSCalendar!
    
    var dateFormatter : NSDateFormatter!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupCalendarView()
        
//        setGre()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension CMDBCalendarView{
    
    func setupCalendarView(){
        
        dataSource = self
        
        delegate   = self
        
        swipeToChooseGesture.enabled = true
        
        allowsMultipleSelection      = true
        
        //      backgroundView.addSubview(calendarView)
        
//        view.addSubview(calendarView)
        
        calendarHeaderView.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.1)
        calendarWeekdayView.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.1)
        
        appearance.eventSelectionColor = UIColor.whiteColor()
        
        appearance.eventOffset = CGPoint(x: 0, y: -7)
        
        today = NSDate()
        
        registerClass(DIYCalendarCell.self, forCellReuseIdentifier: CalendarID)
        
        setGre()
    }
    
    func setGre(){
        
        gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
        
        dateFormatter = NSDateFormatter()
        
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        selectDate((gregorian.dateByAddingUnit(.Day, value: -1, toDate: NSDate(), options: .WrapComponents)), scrollToDate: false)
        selectDate(NSDate(), scrollToDate: false)
        selectDate((gregorian.dateByAddingUnit(.Day, value: 1, toDate: NSDate(), options: .WrapComponents)), scrollToDate: false)
    }

}


extension CMDBCalendarView : FSCalendarDataSource{
    
    func minimumDateForCalendar(calendar: FSCalendar) -> NSDate {
        return dateFormatter.dateFromString("2016-07-08")!
    }
    
    func maximumDateForCalendar(calendar: FSCalendar) -> NSDate {
        return gregorian.dateByAddingUnit(.Day, value: 5, toDate: NSDate(), options: .WrapComponents)!
    }
    
    
    func calendar(calendar: FSCalendar, cellForDate date: NSDate, atMonthPosition position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell = calendar.dequeueReusableCellWithIdentifier(CalendarID, forDate: date, atMonthPosition:position) as! DIYCalendarCell
        return cell
    }
    
    func calendar(calendar: FSCalendar, willDisplayCell cell: FSCalendarCell, forDate date: NSDate, atMonthPosition monthPosition: FSCalendarMonthPosition) {
        configureCell(cell, forData: date, atMonthPosition: monthPosition)
    }
    
    func calendar(calendar: FSCalendar, numberOfEventsForDate date: NSDate) -> Int {
        return 0
    }
}

extension CMDBCalendarView : FSCalendarDelegate{
    
    func calendar(calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
        calendar.frame = CGRect(origin: calendar.frame.origin, size: bounds.size)
        
        
    }
    
    
    func calendar(calendar: FSCalendar, shouldSelectDate date: NSDate, atMonthPosition monthPosition: FSCalendarMonthPosition) -> Bool {
        return monthPosition == .Current
    }
    
    func calendar(calendar: FSCalendar, shouldDeselectDate date: NSDate, atMonthPosition monthPosition: FSCalendarMonthPosition) -> Bool {
        return monthPosition == .Current
    }
    
    func calendar(calendar: FSCalendar, didSelectDate date: NSDate, atMonthPosition monthPosition: FSCalendarMonthPosition) {
        
        configureVisibleCells()
        
    }
    
    func calendar(calendar: FSCalendar, didDeselectDate date: NSDate, atMonthPosition monthPosition: FSCalendarMonthPosition) {
        configureVisibleCells()
    }

}

extension CMDBCalendarView : FSCalendarDelegateAppearance{
    
    func calendar(calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsForDate date: NSDate) -> [UIColor]? {
        if gregorian.isDateInToday(date) {
            return [UIColor.orangeColor()]
        }else{
            return [appearance.eventDefaultColor]
        }
    }
    
}

extension CMDBCalendarView{
    
    func configureCell(cell : FSCalendarCell,forData date : NSDate, atMonthPosition monthPosition : FSCalendarMonthPosition){
        
        let diyCell = cell as! DIYCalendarCell
        
        diyCell.circleImageView.hidden = !gregorian.isDateInToday(date)
        
        if monthPosition == .Current {
            
            var selectionType : SelectionType = .None
            
            if selectedDates.contains(date) {
                
                let previousDate = gregorian.dateByAddingUnit(.Day, value: -1, toDate: date, options: .WrapComponents)
                let nextDate = gregorian.dateByAddingUnit(.Day, value: 1, toDate: date, options: .WrapComponents)
                
                if selectedDates.contains(date) {
                    if selectedDates.contains(previousDate!) && selectedDates.contains(nextDate!) {
                        
                        selectionType = .Middle
                        
                    }else if selectedDates.contains(previousDate!) && selectedDates.contains(date){
                        
                        selectionType = .RightBorder
                        
                    }else if selectedDates.contains(nextDate!){
                        selectionType = .LeftBorder
                    }else{
                        selectionType = .Single
                    }
                }
                
            }else{
                
                selectionType = .None
            }
            
            if selectionType == .None {
                diyCell.selectionLayer.hidden = true
                return
            }
            
            diyCell.selectionLayer.hidden = false;
            diyCell.selectionType = selectionType;
            
            
        }else{
            diyCell.circleImageView.hidden = true;
            diyCell.selectionLayer.hidden = true;
        }
        
    }
    
    func configureVisibleCells(){
        for (_,diyCell) in visibleCells().enumerate() {
            
            //            let date = calendarView.dateForCell(diyCell)
            //
            //            let selectedCell = diyCell as! DIYCalendarCell
            //
            //            print(selectedCell.selectionType.rawValue)
            //
            //            let pos  = calendarView.monthPositionForCell(diyCell)
            //
            //            configureCell(diyCell, forData: date, atMonthPosition: pos)
            
            let selectedCell = diyCell as! DIYCalendarCell
            
            if selectedCell.selectionType != .None && selectedCell.selectionType != .Single {
                print("弹出")
                print(selectedCell.selectionType.rawValue)
            }
            return
            
        }
    }
}
